#!/bin/bash
SpringBoot=$2
heapDumpPath="/mnt/gc/$SpringBoot/"
if [ $1 = "" ]
then
    echo  "not enter start-stop-restart-status"
    exit 1
fi

if [ "$SpringBoot" = "" ]
then
    echo -e "no app name"
    exit 1
fi

function start()
{
    count=`ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l`
    if [ $count != 0 ];then
        echo "$SpringBoot is running..."
    else
         echo "-xx:HeapDumpPath = $heapDumpPath"
         if [ ! -d "$heapDumpPath" ];then
		mkdir -p "$heapDumpPath"
	 fi
         yearMonthDay=`date "+%Y%m%d_%H%M%S"`
         echo "gc log name ==== $yearMonthDay"
         if [ ! -d "${heapDumpPath}gc.${yearMonthDay}.log" ];then
             touch "${heapDumpPath}gc.${yearMonthDay}.log"
         fi
        echo "Start $SpringBoot success..."
         `ls -t | grep $SpringBoot | tail -n +10 | xargs rm -rf`
         BUILD_ID=dontKillMe  nohup java -verbose:gc -Xloggc:"${heapDumpPath}gc.${yearMonthDay}.log" -XX:+UseG1GC -XX:+PrintGCTimeStamps -XX:+PrintGCDetails -XX:+PrintGCDateStamps  -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$heapDumpPath -jar -Dsnow.flake.work.id=1 -Djava.net.preferIPv4Stack=true -Dsnow.flake.datacenter.id=1 $SpringBoot > /home/admin/app.log 2>&1 &
    fi
}

function stop()
{
    echo "Stop $SpringBoot"
    boot_id=`ps -ef |grep java|grep $SpringBoot|grep -v grep|awk '{print $2}'`
    count=`ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l`

    if [ $count != 0 ];then
        kill $boot_id
        count=`ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l`

        boot_id=`ps -ef |grep java|grep $SpringBoot|grep -v grep|awk '{print $2}'`
        kill -9 $boot_id
    fi
}

function restart()
{
    stop
    sleep 2
    start
}

function status()
{
    count=`ps -ef |grep java|grep $SpringBoot|grep -v grep|wc -l`
    if [ $count != 0 ];then
        echo "$SpringBoot is running..."
    else
        echo "$SpringBoot is not running..."
    fi
}

case $1 in
    start)
    start
	;;
    stop)
    stop
	;;
    restart)
    restart
	;;
    status)
    status
	;;
    *)

    echo -e "command not exist"
esac
